package com.ustcinfo.study.mr.r1.zhangshouxin;

import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

public class WorldCount{
    private static  class Mapper extends org.apache.hadoop.mapreduce.Mapper<Object,Text,Text,IntWritable>{
        private  static  final  IntWritable count=new IntWritable(1);

        @Override
        protected void map(Object key, Text value, Context context) throws IOException, InterruptedException {
            String line= value.toString();
            String[] arr=line.split(" ,|，|\\\\s+");
            for (int i = 0; i <arr.length; i++) {
                Text word=new Text();
                word.set(arr[i]);
                context.write(word,count);
            }
        }
    }
    private  static  class  Reducer extends org.apache.hadoop.mapreduce.Reducer<Text,IntWritable,Text,IntWritable>{
        @Override
        protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
            int sum=0;
            for (IntWritable val:values){
                sum +=val.get();
            }
            context.write(key,new IntWritable(sum));
        }
    }

    public static void main(String[] args)throws IOException,ClassNotFoundException,InterruptedException {
        Job job=Job.getInstance();
        job.setJobName("word_count");
        job.setJarByClass(WorldCount.class);
        job.setMapperClass(Mapper.class);
        job.setCombinerClass(Reducer.class);
        job.setReducerClass(Reducer.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);
        FileInputFormat.addInputPath(job,new Path(args[0]));
        FileOutputFormat.setOutputPath(job,new Path(args[1]));
        int status=job.waitForCompletion(true)?0:1;
        System.exit(status);

    }
}
